from . import admin_blue
from info.utils.commons import login_required
from flask import render_template,g,request,current_app,session,redirect,url_for,jsonify
from info.models import User
from info.utils.response_code import RET
import time
from datetime import datetime,timedelta


@admin_blue.route("/index")
@login_required
def index():
    """
    管理员主页
    :return:
    """
    user = g.user
    if not user:
        return render_template("admin/login.html")
    return render_template("admin/index.html", data=user.to_dict())


@admin_blue.route("/login", methods=['GET','POST'])
def login():
    """
    管理员登陆页面
    １　ｇｅｔ，显示登陆页面窗口
    ２　ｐｏｓｔ，校验参数username（输入的为用户的电话号码）,password 完整性
    3  根据username查找对应的user，并核实password
    4　将管理员id nick_name mobile,重要是is_admin
    ５ 返回
    :return:
    """
    if request.method=="GET":
        user_id = session.get('user_id', None)
        is_admin = session.get('is_admin', False)
        if user_id and is_admin:
            return redirect(url_for('admin.index'))
        return render_template('admin/login.html')

    user_name=request.form.get("username")
    password=request.form.get("password")
    if not all([user_name,password]):
        return render_template('admin/login.html', errmsg='参数不完整')
    try:
        user=User.query.filter_by(mobile=user_name,is_admin=True).first()
    except  Exception as e:
        current_app.logger.error(e)
        # errmsg作为模板中的变量，传入将具体数据传入模板中
        return render_template("admin/login.html",errmsg="读取数据库失败")

    if not user or not user.check_password(password):

        return render_template("admin/login.html", errmsg="用户或密码错误")
    session["user_id"]=user.id
    session["mobile"]=user.mobile
    session["nick_name"]=user.nick_name
    session["is_admin"] =user.is_admin
    return redirect(url_for("admin.index"))


@admin_blue.route("/adminlogout")
def logout():
    session.pop("user_id",None)
    session.pop("is_admin",None)
    session.pop("nick_name",None)
    session.pop("mobile",None)

    return jsonify(errno=RET.OK, errmsg="成功退出")


@admin_blue.route("/user_count")
def user_count():
    """
    用户统计
    １　用户总数
    ２　用户月新增数
    ３　用户日新增数
    :return:
    """
    '''用户总数'''
    total_count = 0
    try:
        total_count=User.query.filter(User.is_admin==False).count()

    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR,errmsg="读取数据库失败")
    if not total_count:
        return jsonify(errno=RET.DBERR,errmsg="目前没有用户")


    '''月新增用户数据统计'''
    mon_count=0
    t=time.localtime()
    """
print(t)
time.struct_time(tm_year=2018, tm_mon=9, tm_mday=17, tm_hour=21,
 tm_min=37, tm_sec=10, tm_wday=0, tm_yday=260, tm_isdst=0)
    """
    mon_begin_date_str = "%d-%02d-01" % (t.tm_year,t.tm_mon)
    #将时间字符串转换为时间对象，通过datetime.strptime
    mon_begin_date=datetime.strptime(mon_begin_date_str, "%Y-%m-%d")
    try:
        mon_count=User.query.filter(User.is_admin==False,User.create_time>mon_begin_date).count()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="月增数量读取数据库失败")
    # 不能添加下面的判断换语句，当没有数据时，程序还是要正常显示
    # if not mon_count:
    #     return jsonify(errno=RET.DBERR, errmsg="本月没有新用户")


    '''日增用户'''
    day_count = 0
    day_begin_date_str = "%d-%02d-%02d" % (t.tm_year, t.tm_mon, t.tm_mday)
    # 将时间字符串转换为时间对象，通过datetime.strptime
    day_begin_date = datetime.strptime(day_begin_date_str, "%Y-%m-%d")
    try:
        day_count = User.query.filter(User.is_admin==False,User.create_time > day_begin_date).count()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(RET.DBERR, errmsg="日增数量读取数据库失败")
    # else:day_count=0
    # if not day_count:
    #     return jsonify(errno=RET.DBERR, errmsg="当天没有新用户")
    '''每日用户活跃度
        １　获得当前时间字符串，并转成时间对象，特殊处理当天的时间节点/本计算方式不计算当天
        ２　开始为１６：０：０秒，结束为１７：０：０秒
        ３　根据时间条件提取每日的用户数量
    '''
    time_list=[]
    count_list=[]
    t = time.localtime()
    """
    print(t)
    time.struct_time(tm_year=2018, tm_mon=9, tm_mday=17, tm_hour=21,
    tm_min=37, tm_sec=10, tm_wday=0, tm_yday=260, tm_isdst=0)
    """
    now_time_str = "%d-%02d-%02d" % (t.tm_year, t.tm_mon,t.tm_mday)
    # 错误写法now_tiem_str=time.localtime()
    now_time = datetime.strptime(now_time_str, "%Y-%m-%d")

    for test in range(1,31):
        begin_time=now_time - timedelta(days=test)
        end_time=now_time - timedelta(days=(test-1))
        try:
            count=User.query.filter(User.is_admin==False, User.create_time > begin_time,User.create_time<end_time).count()
        except Exception as e:
            current_app.logger.error(e)
            return jsonify(errno=RET.DBERR, errmsg="每日用户活跃度读取数据库失败")
        '''将时间对象转换为时间字符串，更要注意时间字符串的由来设计'''
        begin_time_str=datetime.strftime(begin_time, '%Y-%m-%d')
        time_list.append(begin_time_str)

        count_list.append(count)

    time_list.reverse()
    count_list.reverse()

    data={
        "total_count":total_count,
        "mon_count":mon_count,
        "day_count":day_count,
        "time_list":time_list,
        "count_list":count_list,
    }
    return render_template("admin/user_count.html", data=data)


@admin_blue.route("/user_list")
def user_list():
    """
    实现用户列表，并分页显示
    :return:
    """
    p = request.args.get("p", 1)
    try:
        p = int(p)
    except Exception as e:
        print("p出现了异常")
        current_app.logger.error(e)
        p = 1
    try:
        paginate = User.query.filter(User.is_admin == False).order_by(User.create_time.desc()).paginate(p, 20, False)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="数据库读取用户列表失败")
    if not paginate:
        return jsonify(errno=RET.DATAERR, errmsg="没有该用户列表")
    total_page = paginate.pages
    current_page = paginate.page
    user_list = paginate.items
    user_dict_list = []
    for user in user_list:
        '''注意news.to_dict()是一个方法，不要忘记括号'''
        user_dict_list.append(user.to_dict())
    data = {
        'user_list': user_dict_list,
        "total_page": total_page,
        "current_page": current_page,
    }
    # 以下操作未能实现分页
    # users = None
    # try:
    #     users = User.query.filter(User.is_admin == False).all()
    #
    # except Exception as e:
    #     current_app.logger.error(e)
    #     return jsonify(errno=RET.DBERR, errmsg="用户数据读取数据库失败")
    # if not users:
    #     return jsonify(errno=RET.DBERR, errmsg="目前没有用户数据")
    # user_info=[]
    # for user in users:
    #     user_info.append(user.to_dict())

    return render_template("admin/user_list.html",data=data)
    pass


@admin_blue.route("/news_review")
def news_review():
    return render_template("admin/news_review.html")
    pass


@admin_blue.route("/news_edit")
def news_edit():

    return render_template("admin/news_edit.html")
    pass


@admin_blue.route("/news_type")
def news_type():


    return render_template("admin/news_type.html")
    pass